/**
 * 通用工具函数
 */
const log4js = require('./log4j');
const jwt = require('jsonwebtoken');
const axios  = require('axios')
const {tcLbsKey,diffIpPlaceByEmail,isGetPlaceId} = require('./../../kum.config')
const transporter = require('./nodemailer')
const {IP_PLACE_DIFF} = require('./mailDemo')
const CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001, // 参数错误
  USER_ACCOUNT_ERROR: 20001, //账号或密码错误
  USER_LOGIN_ERROR: 30001, // 用户未登录
  BUSINESS_ERROR: 40001, //业务请求失败
  AUTH_ERROR: 500001, // 认证失败或TOKEN过期
};
module.exports = {
  /**
   * 分页结构封装
   * @param {number} pageNum
   * @param {number} pageSize
   */
  pager({ pageNum = 1, pageSize = 10 }) {
    pageNum *= 1;
    pageSize *= 1;
    const skipIndex = (pageNum - 1) * pageSize;
    return {
      page: {
        pageNum,
        pageSize,
      },
      skipIndex,
    };
  },
  success(data = '', msg = '', code = CODE.SUCCESS) {
    log4js.debug(data);
    return {
      code,
      data,
      msg,
    };
  },
  fail(msg = '', code = CODE.BUSINESS_ERROR, data = '') {
    log4js.debug(msg);
    return {
      code,
      data,
      msg,
    };
  },
  CODE,
  //   decoded(authorization) {
  //     if (authorization) {
  //       let token = authorization.split(' ')[1];
  //       return jwt.verify(token, 'imooc');
  //     }
  //     return '';
  //   },
  formateDate(date, rule) {
    let fmt = rule || 'yyyy-MM-dd hh:mm:ss';
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, date.getFullYear());
    }
    const o = {
      // 'y+': date.getFullYear(),
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
    };
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const val = o[k] + '';
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1 ? val : ('00' + val).substr(val.length)
        );
      }
    }
    return fmt;
  },
  getIp(req){
    return (req.headers['x-forwarded-for'] ||
      req.connection.remoteAddress ||
      req.socket.remoteAddress ||
      req.connection.socket.remoteAddress).split(':').pop()
  },
  /**
   * @TODO
   * @param ip
   * @returns {Promise<string>}
   */
  async getPlaceByIp(ip){
    if(isGetPlaceId){
      const res = await axios.get(`https://apis.map.qq.com/ws/location/v1/ip?ip=${ip}&key=${tcLbsKey}`)
      let {province,city,district} = res.data.result.ad_info
      return `${province===city?"":province}${city}${district}`
    }
    return " "
  },
  delDifferentPlace(to,last,now,emailConfirmed){
    // 根据配置确定是否开启提醒
    if(!diffIpPlaceByEmail){
      return
    }
    // 检查邮件是否为空 用户可能未绑定 可能未验证
    if((to&& emailConfirmed!==0)){
      // 优先判断地区
      if(last.place!==now.place){
        transporter.sendMail(IP_PLACE_DIFF(to,"地区登录异常","****",now.place))
      }else if(last.ip!==now.ip){
        transporter.sendMail(IP_PLACE_DIFF(to,"ip异常","****",now.place.ip))
      }
    }


  },
  delDate(loginProjection,ret){
    let data = {}
    loginProjection.forEach(item=>{
      data[item] = ret[item]
    })
    return data;
  }
};
